﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using Microsoft.Xna.Framework;

namespace Warlock
{
    class Netcom
    {
        public class Server
        {
            static string dnserver;
            static string dnsmap;
            static bool gameexit = false;
            public Server(String DNS, String Map)
            {
                dnserver = DNS;
                dnsmap = Map;
                StremTCP(7536);
            }
            public Server()
            {
                StremTCP(7536);
            }


            static TcpListener TCP2;
            static Socket TCP3;


            public static void StremTCP(int PORT)
            {
                TcpListener TCPl = null;
                System.Threading.Thread worki;

                worki = new System.Threading.Thread(new System.Threading.ThreadStart(controlconect));
                try
                {
                    IPEndPoint ep = new IPEndPoint(IPAddress.Any, PORT);
                    TCPl = new TcpListener(ep);
                    TCPl.Start();
                    TCP2 = TCPl;
                    worki.Start();
                    if (dnserver != null)
                    {
                        Socket eins = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        eins.Connect(Dns.GetHostEntry(dnserver).AddressList[0], 7536);
                        Send(eins, "newGame:" + dnsmap);
                        eins.Close();
                    }
                }
                catch (SocketException err)
                {
                    Console.WriteLine("ERROR: " + err);
                    Console.ReadLine();
                }

            }

            public static void socketace()
            {
                Recive(TCP3);
            }

            public static void controlconect()
            {
                while (true)
                {

                    if (TCP2.Pending())
                    {
                        System.Threading.Thread worker = new System.Threading.Thread(new System.Threading.ThreadStart(socketace));
                        TCP3 = TCP2.AcceptSocket();
                        worker.Start();
                    }
                    System.Threading.Thread.Sleep(100);
                }

            }

            static string games = "END LIST";
            static int id = 0;
            static int Player = 0;

            public static void Recive(Socket TCP1)
            {
                byte[] byteBuffer;
                int bytesRcvd;
                char[] chars;
                int Playerid = 0;
                String[] SplitPlayerinfo = new String[10];
                String Playerreplaceinfo = "Gamer List";
                while (true)
                {

                    try
                    {
                        byteBuffer = new byte[2048];
                        bytesRcvd = TCP1.Receive(byteBuffer);
                        chars = new char[bytesRcvd];
                        Decoder dec = Encoding.UTF8.GetDecoder();
                        int charLen = dec.GetChars(byteBuffer, 0, bytesRcvd, chars, 0);
                        string newData = new string(chars);
                        
                        if (newData.Length != 0)
                        {
                            StringReader read = new StringReader(newData);
                            while (true)
                            {
                                String newDataline = read.ReadLine();
                                if (newDataline == null)
                                {
                                    break;
                                }
                                if (newDataline.Contains("newPlayer:"))
                                {
                                    games = id.ToString() + ";" + newDataline.Replace("newPlayer:", "") + Environment.NewLine + games;
                                    Playerreplaceinfo = id.ToString() + ";" + newDataline.Replace("newPlayer:", "");
                                    SplitPlayerinfo = newDataline.Split(new char[] { ';' });
                                    Send(TCP1, "ID;" + Playerid.ToString());
                                    Send(TCP1, "Gamer List" + Environment.NewLine + games);
                                    Console.WriteLine("newPlayer: " + newDataline);
                                    Playerid = id;
                                    id++;
                                    Player++;
                                }
                                if (newDataline.Contains("PlayerUpdate:"))
                                {
                                    games = games.Replace(Playerreplaceinfo, newDataline.Replace("PlayerUpdate:", ""));
                                    Playerreplaceinfo = newDataline.Replace("PlayerUpdate:", "");
                                    SplitPlayerinfo = newDataline.Split(new char[] { ';' });
                                }
                                if (newDataline.Contains("PlayerUpdateList"))
                                {
                                    Send(TCP1, "Gamer List" + Environment.NewLine + games);
                                }
                            }
                        }
                    }
                    catch (SocketException se)
                    {
                        Console.WriteLine(se.Message);
                        TCP1.Close();
                        break;
                    }
                    finally
                    {
                        byteBuffer = null;
                        bytesRcvd = 0;
                        chars = null;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }

            public static void Send(Socket TCP1, String text)
            {
                byte[] byteBuffer = System.Text.Encoding.ASCII.GetBytes(Environment.NewLine + text);
                //TCP1.Send(byteBuffer, 0, byteBuffer.Length, SocketFlags.None);
                TCP1.Send(byteBuffer, 0, byteBuffer.Length, SocketFlags.None);
            }


        }
        public class Client
        {
            public static Socket TCP1;
            public static string games = "";
            public static int persid = 0;
            public Client(String IP, int PORT)
            {
                Stream(IP, PORT);
            }
            public static void socketace()
            {
                Recive(TCP1);
            }

            public static void Stream(String IP, int PORT)
            {
                try
                {
                    TCP1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    TCP1.Connect(IPAddress.Parse(IP),7536);
                    System.Threading.Thread worker = new System.Threading.Thread(new System.Threading.ThreadStart(socketace));
                    worker.Start();
                    
                }
                catch (SocketException err)
                {
                    Console.WriteLine("ERROR: " + err);
                    Console.ReadLine();
                }
            }
            public static void Recive(Socket TCP1)
            {
                byte[] byteBuffer;
                int bytesRcvd;
                char[] chars;

                while (true)
                {

                    try
                    {
                        byteBuffer = new byte[2048];
                        bytesRcvd = TCP1.Receive(byteBuffer);
                        chars = new char[bytesRcvd];
                        Decoder dec = Encoding.UTF8.GetDecoder();
                        int charLen = dec.GetChars(byteBuffer, 0, bytesRcvd, chars, 0);
                        string newData = new string(chars);
                        StringReader read = new StringReader(newData);
                        while (true)
                        {
                            String newDataline = read.ReadLine();
                            if (newDataline == null)
                            {
                                break;
                            }
                            if (newData.Length != 0)
                            {
                                if (newDataline.Contains("Gamer List"))
                                {
                                    games = newData.Replace("Gamer List", "");
                                }
                                if (newDataline.Contains("ID;"))
                                {
                                    persid = Convert.ToInt32(newDataline.Replace("ID;", ""));
                                }
                            }
                        }
                    }
                    catch (SocketException se)
                    {
                        Console.WriteLine(se.Message);
                        TCP1.Close();
                        break;
                    }
                    finally
                    {
                        byteBuffer = null;
                        bytesRcvd = 0;
                        chars = null;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            public static void Send(Socket TCP1, String text)
            {
                byte[] byteBuffer = System.Text.Encoding.ASCII.GetBytes(Environment.NewLine + text);
                //TCP1.Send(byteBuffer, 0, byteBuffer.Length, SocketFlags.None);
                TCP1.Send(byteBuffer, 0, byteBuffer.Length, SocketFlags.None);
            }
        }
    }
}
